package com.hdax.dm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.dm.dto.IndexNavDto;
import com.hdax.dm.mappers.ItemTypeMapper;
import com.hdax.dm.mapstrucs.IndexNavDtoMapper;
import com.hdax.dm.service.ItemService;
import com.hdax.dm.service.ItemTypeService;
import com.hdax.dm.entity.item.DmItemType;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ItemTypeSImpl extends ServiceImpl<ItemTypeMapper, DmItemType> implements ItemTypeService {

    @Autowired
    private IndexNavDtoMapper indexNavDtoMapper;

    @Autowired
    private ItemService itemService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public CommonResponse<List<IndexNavDto>> navs() {
        //进入该方法后，先判断缓存中是否存在数据
        List<IndexNavDto> navDtos=null;
        if (redisTemplate.opsForValue().get("index:navs")==null) {
            //封装MP查询条件 wrapper
            QueryWrapper<DmItemType> wrapper=new QueryWrapper();
            wrapper.eq("parent",0L);
        /*
            如果条件满足，就执行。不满足跳过
            wrapper.eq(100>200,"字段名","值");
        */
            List<DmItemType> itemTypes= baseMapper.selectList(wrapper);
            navDtos= indexNavDtoMapper.toTargets(itemTypes);
            for (IndexNavDto navDto: navDtos) {
                QueryWrapper<DmItemType> wrapper2=new QueryWrapper();
                wrapper2.eq("parent",navDto.getId());
                //查询子集
                navDto.setChildren(indexNavDtoMapper.toTargets(baseMapper.selectList(wrapper2)));
                //查询热门商品
                navDto.setHotItems(itemService.items(navDto.getId(), 1L));
            }
            redisTemplate.opsForValue().set("index:navs",navDtos);
        }else {
            navDtos= (List<IndexNavDto>) redisTemplate.opsForValue().get("index:navs");
        }



        return ResponseUtil.returnSuccess(navDtos);
    }

    @Override
    public CommonResponse<List<DmItemType>> lineNav() {
        QueryWrapper<DmItemType> wrapper=new QueryWrapper();
        wrapper.eq("parent",0L);
        List<DmItemType> itemTypes= baseMapper.selectList(wrapper);
        return ResponseUtil.returnSuccess(itemTypes);
    }
}
